import logging
import os
from datetime import datetime

class gl0906_logger:
    def __init__(self, log_dir="logs", max_files=5):
        self.log_dir = log_dir
        self.max_files = max_files
        os.makedirs(self.log_dir, exist_ok=True)
        self.log_file = self.create_log_file()
        self.create_log_header()
        self.setup_logger()

    def create_log_file(self):
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        log_file = os.path.join(self.log_dir, f"log_ait_{timestamp}.log")
        return log_file

    def setup_logger(self):
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s - %(levelname)s - %(module)s : %(message)s',
                            handlers=[logging.FileHandler(self.log_file),
                                      logging.StreamHandler()])

    def cleanup_logs(self):
        log_files = sorted([f for f in os.listdir(self.log_dir) if f.endswith('.log')])
        while len(log_files) > self.max_files:
            os.remove(os.path.join(self.log_dir, log_files.pop(0)))

    def create_log_header(self):
        header = f"""############################################################################################
# Log File Header
############################################################################################
# Description: This log file contains the runtime logs of the GL0906 Auto Integration Tool.
# Created By: GSS
# Created Date: {datetime.now().strftime('%Y-%m-%d')}
# Log Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL
# Format: [%(asctime)s] %(levelname)s in %(module)s: %(message)s
############################################################################################
"""
        with open(self.log_file, 'w') as log_file:
            log_file.write(header + '\n')


def redirect_output_to_log(logger):
    import sys
    class gl0906_logger_writer:
        def __init__(self, level):
            self.level = level
        def write(self, message):
            if message.strip() != "":
                self.level(message)
        def flush(self):
            pass

    sys.stdout = gl0906_logger_writer(logging.info)
    sys.stderr = gl0906_logger_writer(logging.error)
